﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using DingTida.IBLL;
using DingTida.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace DingTida.BLL
{
    public class Msg:IMsg
    {


        public string access_token = "";
        public EasyStarContext db;
        public OapiUserGetuserinfoResponse rsp = null;
        public IMemoryCache Cache;
        public IToken token;
        public ILogger<Msg> log;

        public Msg(EasyStarContext _db, IMemoryCache _cache, IToken _token,ILogger<Msg> _log)
        {
            this.db = _db;
            this.Cache = _cache;
            this.token = _token;
            this.log = _log;
        }
      


        public void SendMsg(string content, string uid)
        {

           if(uid!=null&&uid!=""&&uid!=string.Empty)
            {
                var realuid = db.EmEmpData.Where(c => c.EmpNo == uid).FirstOrDefault();

                if (realuid.DuserName != null && realuid.DuserName != "")
                {


                    IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
                    OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
                    req.AgentId = 699078450L;
                    req.UseridList = realuid.DuserName;
                    OapiMessageCorpconversationAsyncsendV2Request.MsgDomain obj1 = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
                    obj1.Msgtype = "text";
                    OapiMessageCorpconversationAsyncsendV2Request.TextDomain obj2 = new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
                    obj2.Content = content;
                    obj1.Text = obj2;
                    req.Msg_ = obj1;
                    OapiMessageCorpconversationAsyncsendV2Response rsp = client.Execute(req, token.GetToken());
                    if (rsp.IsError)
                    {
                        log.LogError(rsp.Errmsg+rsp.ErrMsg+"content:"+content+"userid:"+uid);

                    }
                    else {
                        log.LogInformation(rsp.Body+ "content:" + content + "userid:" + uid);
                    
                    }

                }

            }

        }
    }
}
